package com.guopiao.vat.service.impl;

import com.guopiao.vat.common.cronjob.YJTaskInforCode;
import com.guopiao.vat.dao.mapper.cluster.SignedDao;
import com.guopiao.vat.dao.mapper.master.YjTaskInfoMapper;
import com.guopiao.vat.service.SignedService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SignedServiceImpl implements SignedService {

    private static Logger _log = LoggerFactory.getLogger(SignedServiceImpl.class);

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");

    @Autowired
    private SignedDao signedDao;

    @Autowired
    private YjTaskInfoMapper yjTaskInfoDao;

    /**
     * 获取所要执行任务的税号
     */
    @Override
    public List<Map<String, Object>> getNsrxxList() {
        return signedDao.getNsrxxList();
    }

    /**
     * 根据税号获取发票未签名张数
     * @param nsrsbh
     * @return
     */
    @Override
    public Long getWqmzsCount(String nsrsbh) {
        return signedDao.getWqmzsCount(nsrsbh);
    }

    /**
     * 根据税号获取未签名数据
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getWqmzsFPHMList(String nsrsbh_str, int num) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("xhdwdm", nsrsbh_str);
        param.put("begin", 0);
        param.put("end", num);
        return signedDao.getWqmzsFPHMList(param);
    }

    /**
     * 添加预警信息
     *
     */
    @Override
    public void updateYjTaskInfo(String nsrsbh, String task_type, List<Map<String, Object>> params) {
        Map<String, Object> deletParam = new HashMap<String, Object>();
        deletParam.put("kpdwdm", nsrsbh);
        deletParam.put("task_type", task_type);

        yjTaskInfoDao.delYjTaskInfo(deletParam);
        if (CollectionUtils.isEmpty(params))
        {
            return;
        }
        for (Map<String, Object> map : params)
        {
            map.put("kpdwdm", nsrsbh);
            map.put("task_type", task_type);
            yjTaskInfoDao.insertYjTaskInfo(map);
        }
    }

    /**
     * 获取未签名张数提醒预警值
     *
     * @param nsrsbh
     * @return
     */
    @Override
    public String getWQMZSWarningNum(String nsrsbh)
    {
        return "10000";
    }

    /**
     * 根据税号获取未签名数据的数量和机器编号
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> getInvoiceLists(String nsrsbh) {
        return signedDao.getInvoiceLists(nsrsbh);
    }

    @Override
    public void UnsignedJob() {
        Set<String> needSendYjNsrsbhList = new HashSet<String>();
        List<Map<String, Object>> nsr_list = signedDao.getNsrxxList();
        if (!CollectionUtils.isEmpty(nsr_list))
        {
            String nsrsbh = "";
            String nsr_sc = "";
            String kpdwmc = "";

            for (Map<String, Object> map : nsr_list)
            {

                nsrsbh = String.valueOf(map.get("kpdwdm"));
                kpdwmc = String.valueOf(map.get("kpdwmc"));
                //获取未签名张数提醒预警值
                nsr_sc = getWQMZSWarningNum(nsrsbh);
                //根据税号获取未签名数据的数量和机器编号
                List<Map<String, Object>> invoiceLists = signedDao.getInvoiceLists(nsrsbh);

                for (Map<String, Object> listss : invoiceLists)
                {
                    Long count = (Long) listss.get("count");
                    //Long count = unsignedJob.signedService.getWqmzsCount(nsrsbh);
                    List<Map<String, Object>> yjtaskInfors = new ArrayList<Map<String, Object>>();
                    Map<String, Object> taskInfor = new HashMap<String, Object>();
                    boolean sendYj = false;
                    taskInfor.put("kpdwmc", kpdwmc);
                    taskInfor.put("yjz", nsr_sc);
                    taskInfor.put("value", count);
                    taskInfor.put("jqbh",listss.get("jqbh"));

                    if (count <= Long.valueOf(nsr_sc))
                    {

                        _log.info(nsrsbh + "发票未签名张数(" + count + ")未达到预警值(" + nsr_sc + ")");

                    }
                    else
                    {
                        sendYj = true;
                        List<Map<String, Object>> list = getWqmzsFPHMList(nsrsbh, 3);

                        List<String> fphmArray = new ArrayList<String>();
                        for (Map<String, Object> fphm : list)
                        {
                            fphmArray.add(String.valueOf(fphm.get("fphm")));
                        }
                        taskInfor.put("fphm", StringUtils.join(fphmArray, ","));
                        needSendYjNsrsbhList.add(nsrsbh);
                    }

                    taskInfor.put("status", sendYj ? "1" : "0");
                    yjtaskInfors.add(taskInfor);
                    //添加预警信息
                    updateYjTaskInfo(nsrsbh, YJTaskInforCode.WQM_CODE, yjtaskInfors);
                }
            }
        }
    }

    @Override
    public void SignedNoUploadJob() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, -1);
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy/MM/dd");
        Set<String> needSendYjNsrsbhList=new HashSet<String>();
        List<Map<String, Object>> nsr_list = getNsrxxList();
        if (!CollectionUtils.isEmpty(nsr_list))
        {
            String nsrsbh = "";
            String kpdwmc = "";
            for (Map<String, Object> map : nsr_list)
            {
                nsrsbh = String.valueOf(map.get("kpdwdm"));
                kpdwmc = String.valueOf(map.get("kpdwmc"));
                Map<String, Object> info_map = getWscAcountList(nsrsbh);
                String monthDate = "";
                List<Map<String, Object>> yjtaskInfors = new ArrayList<Map<String, Object>>();
                Map<String, Object> taskInfor = new HashMap<String, Object>();
                boolean sendYj = false;
                String skserver_yjz = "";
                String dqValue = "";
                String yjrq = "";
                taskInfor.put("kpdwmc", kpdwmc);

                if (info_map.get("scjzrq") == null || info_map.get("scjzrq").equals("")
                        || info_map.get("scjzrq").equals("0"))
                {
                    _log.info(nsrsbh + "scjzrq未设置");
                }
                else
                {

                    skserver_yjz = String.valueOf(info_map.get("scjzrq"));
                    Calendar nowCal = Calendar.getInstance();

                    int scjzrq = Integer.valueOf(skserver_yjz);
                    Calendar thisMonthSCJZRQCal = Calendar.getInstance();

                    thisMonthSCJZRQCal.set(Calendar.DAY_OF_MONTH, scjzrq);
                    Calendar lastSCJZRQCal = Calendar.getInstance();
                    lastSCJZRQCal.setTime(thisMonthSCJZRQCal.getTime());
                    lastSCJZRQCal.add(Calendar.MONTH, -1);
                    Calendar nextSCJZRQCal = Calendar.getInstance();
                    nextSCJZRQCal.setTime(thisMonthSCJZRQCal.getTime());
                    nextSCJZRQCal.add(Calendar.MONTH, 1);
                    int yjDate = 0;
                    int wscNum = 0;
                    // 假设截止日期是5号，本月是6月，那么上个月发票截止日期是6月5号，这个月是7月5号，下个月是8月5号，
                    // 7月4号检查6月的未上传数量；8月4号检查7月份未上传数量。
                    // 即6月6号到7月5号检查6月份未上传，7月6号到8月5号检查7月份未上传。

                    // 如果当前时间小于等于这个月截止日期，那么处理上个月的未上传情况。否则处理这个月的未上传情况
                    if (!nowCal.getTime().after(thisMonthSCJZRQCal.getTime()))
                    {
                        // 当前时间肯定比月初大，处理6月1号到6月5号，比截止日期小

                        // 今天是6月4，处理5月份未上传,截止日期是6月5号，检查日期是6月4号

                        Calendar now = Calendar.getInstance();
                        now.add(Calendar.MONTH, -1);
                        monthDate = simpleDateFormat.format(now.getTime()).substring(4, 6);
                        wscNum = Integer.valueOf(info_map.get("lastMonthNum").toString());
                        thisMonthSCJZRQCal.add(Calendar.DATE, -1);
                        yjDate = thisMonthSCJZRQCal.get(Calendar.DATE);
                        yjrq = simpleDateFormat2.format(thisMonthSCJZRQCal.getTime());

                    }
                    else
                    {
                        // 当前时间日期肯定比截止日期大，小于月末，处理本月未上传情况

                        // 今天是6月30号，处理6月份未上传,截止日期是7月5号，检查日期是7月4号
                        Calendar now = Calendar.getInstance();
                        monthDate = simpleDateFormat.format(now.getTime()).substring(4, 6);
                        wscNum = Integer.valueOf(info_map.get("thisMonthNum").toString());
                        nextSCJZRQCal.add(Calendar.DATE, -1);
                        yjDate = nextSCJZRQCal.get(Calendar.DATE);
                        yjrq = simpleDateFormat2.format(nextSCJZRQCal.getTime());

                    }
                    dqValue = String.valueOf(wscNum);

                    if (nowCal.get(Calendar.DATE) != yjDate)
                    {
                        _log.info("发票上传截止日期预警未达到预警日期" + yjDate + ",当前上传截止日期：" + scjzrq);

                    }
                    else
                    {
                        if (wscNum > 0)
                        {
                            sendYj = true;
                            needSendYjNsrsbhList.add(nsrsbh);

                        }
                        else
                        {
                            _log.info("发票已全部上传");
                        }
                    }

                }
                taskInfor.put("value", dqValue);
                taskInfor.put("yjz", yjrq);
                taskInfor.put("yj_month", monthDate);
                taskInfor.put("skserver_yjz", skserver_yjz);
                taskInfor.put("status", sendYj ? "1" : "0");
                yjtaskInfors.add(taskInfor);
                updateYjTaskInfo(nsrsbh, YJTaskInforCode.FPSCJZRQ_CODE, yjtaskInfors);
            }
        }
    }

    @Override
    public Map<String, Object> getWscAcountList(String nsrsbh)
    {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        String now_date_str = simpleDateFormat.format(cal.getTime());
        cal.add(Calendar.MONTH, -1);
        String date_str = simpleDateFormat.format(cal.getTime());
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("nsrsbh", nsrsbh);
        param.put("lastMonthDate", date_str);
        param.put("thisMonthDate", now_date_str);
        return signedDao.getWscAcountList(param);
    }

    @Override
    public void checkSignFailJob() {
        Set<String> needSendYjNsrsbhList = new HashSet<String>();
        List<Map<String, Object>> nsr_list = getNsrxxList();
        if (!CollectionUtils.isEmpty(nsr_list))
        {
            String nsrsbh = "";
            String nsr_sc = "";
            String kpdwmc = "";

            for (Map<String, Object> map : nsr_list)
            {
                nsrsbh = String.valueOf(map.get("kpdwdm"));
                kpdwmc = String.valueOf(map.get("kpdwmc"));
                nsr_sc = getQMSBZSWarningNum(nsrsbh);
                //根据税号获取未签名数据的数量和机器编号
                List<Map<String, Object>> invoiceLists = signedDao.getSignedFails(nsrsbh);
                for (Map<String, Object> maps : invoiceLists){
                    Long count = (Long) maps.get("count");
                    List<Map<String, Object>> yjtaskInfors = new ArrayList<Map<String, Object>>();
                    Map<String, Object> taskInfor = new HashMap<String, Object>();
                    boolean sendYj = false;
                    taskInfor.put("kpdwmc", kpdwmc);
                    taskInfor.put("yjz", nsr_sc);
                    taskInfor.put("value", count);
                    taskInfor.put("jqbh",maps.get("jqbh"));
                    if (count <= Long.valueOf(nsr_sc))
                    {
                        _log.info(nsrsbh + "发票验签失败预警(" + count + ")未达到预警值(" + nsr_sc + ")");
                    }
                    else
                    {
                        sendYj = true;
                        List<Map<String, Object>> list = signedDao.getQmsbzsFPHMList(nsrsbh, 3);
                        List<String> fphmArray = new ArrayList<String>();
                        for (Map<String, Object> fphm : list)
                        {
                            fphmArray.add(String.valueOf(fphm.get("fphm")));
                        }
                        taskInfor.put("fphm", StringUtils.join(fphmArray, ","));
                        needSendYjNsrsbhList.add(nsrsbh);
                    }
                    taskInfor.put("status", sendYj ? "1" : "0");
                    yjtaskInfors.add(taskInfor);
                    updateYjTaskInfo(nsrsbh, YJTaskInforCode.YQSB_CODE, yjtaskInfors);
                }
            }
        }
    }

    @Override
    public void checkSignSuccessJob() {
        List<Map<String, Object>> nsr_list = getNsrxxList();
        if (!CollectionUtils.isEmpty(nsr_list))
        {
            String nsrsbh = "";
            String nsr_sc = "";
            String kpdwmc = "";

            for (Map<String, Object> map : nsr_list)
            {
                nsrsbh = String.valueOf(map.get("kpdwdm"));
                kpdwmc = String.valueOf(map.get("kpdwmc"));
                nsr_sc = getQMSBZSWarningNum(nsrsbh);
                //根据税号获取未签名数据的数量和机器编号
                List<Map<String, Object>> invoiceLists = signedDao.getSignedSucc(nsrsbh);
                for (Map<String, Object> maps : invoiceLists){
                    Long count = (Long) maps.get("count");
                    List<Map<String, Object>> yjtaskInfors = new ArrayList<Map<String, Object>>();
                    Map<String, Object> taskInfor = new HashMap<String, Object>();
                    boolean sendYj = false;
                    taskInfor.put("kpdwmc", kpdwmc);
                    taskInfor.put("yjz", nsr_sc);
                    taskInfor.put("value", count);
                    taskInfor.put("jqbh",maps.get("jqbh"));

                    if (count <= Long.valueOf(nsr_sc))
                    {
                        _log.info(nsrsbh + "发票验签失败预警(" + count + ")未达到预警值(" + nsr_sc + ")");
                    }
                    else
                    {
                        sendYj = true;
                        List<Map<String, Object>> list = signedDao.getQmsbzsFPHMList(nsrsbh, 3);
                        List<String> fphmArray = new ArrayList<String>();
                        for (Map<String, Object> fphm : list)
                        {
                            fphmArray.add(String.valueOf(fphm.get("fphm")));
                        }
                        taskInfor.put("fphm", StringUtils.join(fphmArray, ","));
                    }
                    taskInfor.put("status", sendYj ? "1" : "0");
                    yjtaskInfors.add(taskInfor);
                    updateYjTaskInfo(nsrsbh, YJTaskInforCode.YQSB_CODE, yjtaskInfors);
                }
            }
        }
    }

    /**
     * 获取签名失败张数提醒预警值
     *
     * @param nsrsbh
     * @return
     */
    public String getQMSBZSWarningNum(String nsrsbh)
    {
        return "100000";
    }
}
